#! /bin/mksh

# `mv` call is interactive on overwrite, beware of halts

FNAME="$1"
# ARGMIME=$(file -e text -ib "$1" | sed -e 's/\; .*$//')
ARGMIME=$(file -b --mime-type -e text -e elf "$1")

comparetype ()
{
	match="$(echo "$FNAME" | egrep -i "$1")"

	if [ "$match" ]
	then
#		echo "Filename is ok"
		exit 0
	else
		echo "MISMATCH: $FNAME, adding suffix $2"
		mv -i "$FNAME" "$FNAME"."$2"
	fi
}

case "$ARGMIME"
{
	# image/
	"image/jpeg")                    comparetype "\.(jpg|jpeg|jpe)$"   "jpg"     ;;
	"image/png")                     comparetype "\.png$"              "png"     ;;
	"image/gif")                     comparetype "\.gif$"              "gif"     ;;
	"image/webp")                    comparetype "\.webp$"             "webp"    ;;

	# video/
	"video/x-matroska")              comparetype "\.mkv$"              "mkv"     ;;
	"video/webm")                    comparetype "\.webm$"             "webm"    ;;
	"video/mp4")                     comparetype "\.mp4$"              "mp4"     ;;
	"video/x-m4v")                   comparetype "\.m4v$"              "m4v"     ;;
	"video/3gpp")                    comparetype "\.3gp$"              "3gp"     ;;
	"video/quicktime")               comparetype "\.mov$"              "mov"     ;;

	# audio/
	"audio/ogg")                     comparetype "\.(ogg|opus)$"       "ogg"     ;;
	"audio/mpeg")                    comparetype "\.mp3$"              "mp3"     ;;
	"audio/x-wav")                   comparetype "\.wav$"              "wav"     ;;

	# misc
	"application/json")              comparetype "\.json$"             "json"    ;;
	"application/pdf")               comparetype "\.pdf$"              "pdf"     ;;
	"application/x-bittorrent")      comparetype "\.torrent$"          "torrent" ;;
	"application/x-shockwave-flash") comparetype "\.swf$"              "swf"     ;;
	"application/x-sqlite3")         comparetype "\.(sqlite|db)$"      "db"      ;;
	"image/vnd.djvu")                comparetype "\.djvu$"             "djvu"    ;;

	# Used as multiple formats, not renaming
	"application/zip")               exit 0                                      ;;
	"application/octet-stream")      exit 0                                      ;;
	"text/plain")                    exit 0                                      ;;
	"video/x-ms-asf")                exit 0                                      ;;
	*) echo "Unaccounted MIME type: $ARGMIME for file $FNAME"                    ;;
}
